﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using USERS.CYT369.COM.MODELS.Brand;

namespace USERS.CYT369.COM.DAL
{
    public class BrandService : USERS.CYT369.COM.DAL.DbContexts.BrandBaseService<BrandService>
    {
        public BrandService() { }

        #region Brand
        /// <summary>
        /// 保存品牌信息
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public bool SaveBrand(USERS.CYT369.COM.MODELS.Brand.Brand brand)
        {
            brand.EditDate = DateTime.Now;
            using (var ctx = this.BrandCtx)
            {
                var item = ctx.Brands.Where(b=>b.Id==brand.Id).Include(b => b.BrandExtension).Include(b=>b.Category).FirstOrDefault();
                if (item == null)
                {
                    brand.CreateDate = DateTime.Now;
                    brand.CreatorName = brand.EditorName;
                    brand.CreatorFullName = brand.EditorFullName;
                    brand.EditorName = brand.EditorName;
                    brand.EditorFullName = brand.EditorFullName;
                    brand.EditDate = brand.CreateDate;
                    brand.ReviewResult = -2;
                    brand.InquiryCount = 0;
                    brand.CategoryID = brand.CategoryID <= 0 ? null : brand.CategoryID;
                    ctx.Brands.Add(brand);
                }
                else
                {
                    item.FranchiseRegionID = brand.FranchiseRegionID<=0?null: brand.FranchiseRegionID;
                    item.CategoryID = brand.CategoryID<=0?null:brand.CategoryID;

                    item.Name = brand.Name;
                    item.Amount = brand.Amount;
                    item.StoreCount = brand.StoreCount;
                    item.MainProduct = brand.MainProduct;
                    item.TargetAudience = brand.TargetAudience;
                    item.DevelopmentModel = brand.DevelopmentModel;
                    item.FranchiseWebsite = brand.FranchiseWebsite;
                    item.Brief=brand.Brief;

                    item.EditorID = brand.EditorID;
                    item.EditorName = brand.EditorName;
                    item.EditorFullName = brand.EditorFullName;
                    item.EditDate = brand.EditDate;

                    item.ReviewResult = -2;

                    item.BrandExtension.FranchiseProcess = brand.BrandExtension.FranchiseProcess;
                    item.BrandExtension.FranchiseAdvantages = brand.BrandExtension.FranchiseAdvantages;
                    item.BrandExtension.FranchiseConditions = brand.BrandExtension.FranchiseConditions;
                    item.BrandExtension.BrandDetails = brand.BrandExtension.BrandDetails;
                    
                }

                ctx.SaveChanges();

                return true;
            }
        }

        /// <summary>
        /// 保存品牌图片
        /// </summary>
        /// <param name="brandImage"></param>
        /// <returns></returns>
        public bool SaveBrandImage(USERS.CYT369.COM.MODELS.Brand.BrandImage brandImage)
        {
            brandImage.ChangedTime = DateTime.Now;
            using (var ctx = this.BrandCtx)
            {
                var brand = ctx.Brands.Where(c => c.Id == brandImage.BrandID).FirstOrDefault();
                if (brand != null)
                {
                    brand.ReviewResult = -2;
                    var item = ctx.BrandImages.Where(c => c.Id == brandImage.Id).FirstOrDefault();
                    if (item == null)
                    {
                        ctx.BrandImages.Add(brandImage);
                    }
                    else
                    {
                        item.OrderNumber = brandImage.OrderNumber;
                        item.FileExtension = brandImage.FileExtension;
                        item.ImagePath = brandImage.ImagePath;

                        item.ChangedTime = DateTime.Now;
                    }

                    ctx.SaveChanges();
                }
                return true;
            }
        }

        /// <summary>
        /// 删除图片资源
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool BrandImageDelete(long brandId, long fileId, long userId)
        {
            using (var ctx = this.BrandCtx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandImages)
                                where o.Id == brandId && o.EditorID == userId
                                select o).FirstOrDefault();

                {
                    var image = (from o in brand.BrandImages
                                      where o.Id == fileId
                                      select o).FirstOrDefault();

                    if (image != null)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(image.ImagePath))
                            {
                                USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.BrandInternalBucket, image.ImagePath);
                            }
                        }
                        catch { }

                        ctx.BrandImages.Remove(image);
                        ctx.SaveChanges();

                        return true;
                    }
                }
            }

            return false;
        }


        /// <summary>
        /// 查询品牌信息
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public USERS.CYT369.COM.MODELS.Brand.Brand GetBrandByID(long brandId)
        {
            using (var ctx = this.BrandCtx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandExtension).Include(c => c.Category)
                             where o.Id == brandId && o.IsDeleted == false
                             select o).FirstOrDefault();

                return brand;
            }
        }


        /// <summary>
        /// 查询品牌信息（包含图片）
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public USERS.CYT369.COM.MODELS.Brand.Brand GetBrandByID_IncludeImg(long brandId)
        {
            using (var ctx = this.BrandCtx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandExtension).Include(c => c.BrandImages).Include(c=>c.Category)
                                where o.Id == brandId && o.IsDeleted == false
                             select o).FirstOrDefault();

                return brand;
            }
        }

        /// <summary>
        /// 删除品牌
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool BrandDelete(long brandId)
        {
            using (var ctx = this.BrandCtx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandExtension).Include(c => c.BrandImages)
                                where o.Id == brandId
                                select o).FirstOrDefault();

                if (brand != null)
                {
                    if (brand.InquiryCount > 0)
                    {
                        brand.IsDeleted = true;
                        ctx.SaveChanges();
                    }
                    else
                    {
                        #region 移除OSS上的文件
                        if (brand.BrandImages != null)
                        {
                            foreach (var files in brand.BrandImages)
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(files.ImagePath))
                                    {
                                        USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.BrandInternalBucket, files.ImagePath);
                                    }
                                }
                                catch { }
                            }
                        }
                        #endregion

                        ctx.Brands.Remove(brand);
                        ctx.SaveChanges();
                    }

                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool SubmitAudit(long brandId, long userId)
        {
            using (var ctx = this.BrandCtx)
            {
                var item = (from o in ctx.Brands.Include(c => c.BrandExtension)
                            where o.Id == brandId && o.EditorID == userId
                            select o).FirstOrDefault();

                if (item != null)
                {
                    if (string.IsNullOrEmpty(item.Name) || item.Name == "[未命名]") { return false; }
                    if (item.Amount == 0){ return false; }
                    if (item.BrandExtension == null) { return false; }
                    if (string.IsNullOrEmpty(item.BrandExtension.BrandDetails)
                        && string.IsNullOrEmpty(item.BrandExtension.FranchiseProcess)
                        && string.IsNullOrEmpty(item.BrandExtension.FranchiseConditions)
                        && string.IsNullOrEmpty(item.BrandExtension.FranchiseAdvantages)) { return false; }

                    item.ReviewResult = 0;
                }
                else
                {
                    return false;
                }

                ctx.SaveChanges();

                return true;
            }
        }

        /// <summary>
        /// 获取所有的品牌
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="total"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public IQueryable<USERS.CYT369.COM.MODELS.Brand.Brand> GetBrands(int page, int rows, ref int total, long userId,
                                                                                 int? status = null, string name = null,
                                                                                 int? year = null, int? month = null,
                                                                                 int? categoryID = null)
        {
            using (BrandCtx)
            {
                var items = BrandCtx.Brands
                    .Include(b=>b.BrandImages)
                    .Include(c => c.Category)
                    .ThenInclude(d => d.Parent)
                    .Where(c => c.EditorID == userId && c.IsDeleted == false);
                if (status.HasValue)
                {
                    items = items.Where(c => c.ReviewResult == status.Value);
                }

                if (year.HasValue)
                {
                    items = items.Where(c => c.CreateDate.Year == year.Value);
                }

                if (month.HasValue)
                {
                    items = items.Where(c => c.CreateDate.Month == month.Value);
                }

                if (categoryID.HasValue)
                {
                    items = items.Where(i=>i.CategoryID==categoryID);
                }

                if (!string.IsNullOrEmpty(name))
                {
                    items = items.Where(c => c.Name.Contains(name));
                }

                return items = this.Pagination(page, rows, ref total, items, c => c.Id);
            }
        }

        /// <summary>
        /// 获取品牌统计
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public USERS.CYT369.COM.MODELS.Brand.BrandStastics GetBrandStastics(long userId)
        {
            var items = base.Get<USERS.CYT369.COM.MODELS.Brand.Brand>(c => c.EditorID == userId);

            var stastics = new USERS.CYT369.COM.MODELS.Brand.BrandStastics()
            {
                Total = items.Where(c => c.IsDeleted == false).Count(),
                PassedAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == 1).Count(),
                FailedAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == -1).Count(),
                AwaitAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == 0).Count(),
                Draft = items.Where(c => c.IsDeleted == false && c.ReviewResult == -2).Count(),
                YearGroup = (from o in items
                             group o by o.CreateDate.Year into go
                             select go.Key).ToArray(),

                MonthGroup = (from o in items
                              group o by o.CreateDate.Month into go
                              select go.Key).ToArray()
            };

            return stastics;
        }
        #endregion

        /// <summary>
        /// 获取类别 通过父级ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IQueryable<USERS.CYT369.COM.MODELS.Brand.Category> CategorysGetByParentID(int id)
        {
                var categorys =base.Get<USERS.CYT369.COM.MODELS.Brand.Category>().Where(c=>c.ParentID==id);
                return categorys;
        }
    }
}
